import 'package:flame/game.dart';
import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/material.dart';
// import 'package:flutter/widgets.dart';
import 'GameBuild.dart';
import 'GameOverOverlay.dart';
import 'GameWrapper.dart';
import 'HomeScreen.dart';
import 'LevelSelectionScreen.dart';
import 'PauseOverlay.dart';


void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '耄耋消除',
      debugShowCheckedModeBanner: false,
      home: GameApp(),
    );
  }
}

void initBgm() async{
  FlameAudio.bgm.initialize();
  FlameAudio.bgm.play('bgm1.mp3');
}

class GameApp extends StatefulWidget {
  @override
  State<GameApp> createState() => _GameAppState();
}

class _GameAppState extends State<GameApp> {

  // 当前显示的页面
  late Widget _currentPage;

  // 关卡配置数据
  static const List<LevelConfig> _levels = [
    LevelConfig(1, 'Level 1', 60, 500),
    LevelConfig(2, 'Level 2', 50, 600),
    LevelConfig(3, 'Level 3', 40, 700),
    LevelConfig(4, 'Level 4', 60, 800),
    LevelConfig(5, 'Level 5', 50, 900),
  ];

  // 启动游戏
  void _startGame([int levelIndex = 0]) {
    final level = _levels[levelIndex];
    setState(() {
      _currentPage = GameScreen(
        level: level,
        onGameEnd: _onGameEnd,
      );
    });
  }

  // 显示首页
  void _showHome() {
    setState(() {
      _currentPage = HomeScreen(
        onStartGame: _startGame,
        onLevelSelect: _showLevelSelection,
      );
    });
  }

  // 显示关卡选择界面
  void _showLevelSelection() {
    setState(() {
      _currentPage = LevelSelectionScreen(
        onLevelSelected: (level) {
          _startGame(level - 1);
        },
        onBackToHome: _showHome, // 传递返回首页的回调
      );
    });
  }

  // 游戏结束回调
  void _onGameEnd() {
    // 可以在这里处理游戏结束逻辑
    _showHome();
  }

  @override
  void initState() {
    super.initState();
    // 初始化显示首页
    _currentPage = HomeScreen(
      onStartGame: _startGame,
      onLevelSelect: _showLevelSelection,
    );
    FlameAudio.bgm.initialize();
    FlameAudio.bgm.play('bgm1.mp3');
  }

  @override
  Widget build(BuildContext context) {
    return _currentPage;
  }
}

// 关卡配置类
class LevelConfig {
  final int index;
  final String name;
  final int time;
  final int targetScore;

  const LevelConfig(this.index, this.name, this.time, this.targetScore);
}

// 游戏屏幕组件
class GameScreen extends StatefulWidget {
  final LevelConfig level;
  final Function() onGameEnd;

  const GameScreen({
    super.key,
    required this.level,
    required this.onGameEnd,
  });

  @override
  State<GameScreen> createState() => _GameScreenState();
}

class _GameScreenState extends State<GameScreen> {
  late MyGame _game;
  double _topPadding = 0;

  @override
  void initState() {
    super.initState();
    // 初始化游戏，但暂时不设置topPadding
    _game = MyGame(_topPadding, widget.level, _onGameFinished);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 在这里安全地获取MediaQuery数据
    _topPadding = MediaQuery.of(context).padding.top;
    // 更新游戏中的topPadding
    _game.topPadding = _topPadding;
  }

  void _onGameFinished() {
    widget.onGameEnd();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // 点击返回键时回到首页
        widget.onGameEnd();
        return false;
      },
      child: Scaffold(
        body: SafeArea(
          child: LayoutBuilder(
            builder: (context, constraints) {
              return GameWidget(
                game: _game,
                overlayBuilderMap: <String, Widget Function(BuildContext, Game)>{
                  'gameOver': (context, game) => GameOverOverlay(game),
                  'pause': (context, game) => PauseOverlay(game), // 确保暂停弹窗正确注册
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

class MyGame extends FlameGame {
  double topPadding;
  final LevelConfig level;
  final Function() onGameFinished;

  MyGame(this.topPadding, this.level, this.onGameFinished);

  @override
  Future<void> onLoad() async {
    await super.onLoad();

    // 添加 GameWrapper 并传入所有必需参数
    add(GameWrapper(
      child: GameBoard(),
      levelName: level.name,
      totalTime: level.time,
      targetScore: level.targetScore, // 传递目标得分
      onPaused: () {
        print('Game paused');
        // 暂停游戏逻辑
        // FlameAudio.bgm.pause(); // 音频暂停已经在GameWrapper中处理
      },
      onHome: () {
        print('Returning to home');
        onGameFinished();
      },
      topPadding: topPadding, // 传递顶部安全区高度
    ));
  }
  
  // 重新开始游戏
  void restartGame() {
    // 移除旧的游戏板和包装器
    final gameWrapper = children.whereType<GameWrapper>().firstOrNull;
    if (gameWrapper != null) {
      final gameBoard = gameWrapper.children.whereType<GameBoard>().firstOrNull;
      if (gameBoard != null) {
        gameBoard.removeFromParent();
      }
      gameWrapper.removeFromParent();
    }
    
    // 添加新的游戏包装器和游戏板
    add(GameWrapper(
      child: GameBoard(),
      levelName: level.name,
      totalTime: level.time,
      targetScore: level.targetScore,
      onPaused: () {
        print('Game paused');
      },
      onHome: () {
        print('Returning to home');
        onGameFinished();
      },
      topPadding: topPadding,
    ));
  }
  
  // 进入下一关
  void nextLevel() {
    // 移除旧的游戏板和包装器
    final gameWrapper = children.whereType<GameWrapper>().firstOrNull;
    if (gameWrapper != null) {
      final gameBoard = gameWrapper.children.whereType<GameBoard>().firstOrNull;
      if (gameBoard != null) {
        gameBoard.removeFromParent();
      }
      gameWrapper.removeFromParent();
    }
    
    // 计算下一关卡索引
    int nextLevelIndex = level.index;
    if (level.index < 5) { // 假设最多5关
      nextLevelIndex = level.index + 1;
    }
    
    // 获取下一关配置
    const levels = [
      LevelConfig(1, 'Level 1', 60, 500),
      LevelConfig(2, 'Level 2', 50, 600),
      LevelConfig(3, 'Level 3', 40, 700),
      LevelConfig(4, 'Level 4', 60, 800),
      LevelConfig(5, 'Level 5', 50, 900),
    ];
    
    final nextLevelConfig = levels[nextLevelIndex - 1];
    
    // 添加新的游戏包装器和游戏板
    add(GameWrapper(
      child: GameBoard(),
      levelName: nextLevelConfig.name,
      totalTime: nextLevelConfig.time,
      targetScore: nextLevelConfig.targetScore,
      onPaused: () {
        print('Game paused');

      },
      onHome: () {
        print('Returning to home');
        onGameFinished();
      },
      topPadding: topPadding,
    ));
  }
}